﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.BasicData.EntityFrameworkCore;
using mozhi.smarterp.BasicData.Enums;
using mozhi.smarterp.BasicData.NumberRules;
using mozhi.smarterp.BasicData.NumberRules.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.BasicData.Repositories
{
    public class DocumentNumberRuleRepository : EfCoreRepository<BasicDataDbContext, DocumentNumberRule, Guid>, IDocumentNumberRuleRepository
    {
        public DocumentNumberRuleRepository(IDbContextProvider<BasicDataDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<int> GetCountAsync(DocumentType type, bool? isDefault, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<DocumentNumberRule>().AsNoTracking()
                .Where(x => x.Type == type)
                .WhereIf(isDefault.HasValue, x => x.IsDefault == true)
                .CountAsync();


            return count;
        }

        public async Task<List<DocumentNumberRule>> GetListAsync(DocumentType type, bool? isDefault, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var rules = await dbContext.Set<DocumentNumberRule>().AsNoTracking()
                .Where(x => x.Type == type)
                .WhereIf(isDefault.HasValue, x => x.IsDefault == true)
                .ToListAsync();


            return rules;
        }
    }
}
